import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import '../assets/styles/LoginStyles.css';

const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const history = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('http://localhost:5000/api/auth/login', { email, password });
      const { token,role } = response.data;

      // 存储 token 到 localStorage 或 sessionStorage
      localStorage.setItem('token', token);
      // 根据角色跳转
    if (role === '管理员') {
      history('/admin');
    } else if (role === '商家') {
      history('/merchant');
    } else {
      history('/home');
    }

      // // 跳转到用户首页
      // history('/home'); // 假设用户首页路径为 '/home'
    } catch (error) {
      console.error('登录失败:', error.response?.data || error.message);
      setErrorMessage(error.response?.data?.message || '登录失败');
    }
  };

  return (
    <div className="login-container">
      <div className="login-card">
        <h2 className="login-title">登录</h2>
        <form onSubmit={handleSubmit}>
          <div className="login-form-group">
            <label htmlFor="email">邮箱:</label>
            <input 
              type="email" 
              id="email" 
              className="login-input" 
              value={email} 
              onChange={(e) => setEmail(e.target.value)} 
              required 
            />
          </div>
          <div className="login-form-group">
            <label htmlFor="password">密码:</label>
            <input 
              type="password" 
              id="password" 
              className="login-input" 
              value={password} 
              onChange={(e) => setPassword(e.target.value)} 
              required 
            />
          </div>
          <button type="submit" className="login-button">登录</button>
          <p>
            还没有账号？<a href="/register" className="login-link">注册</a>
          </p>
        </form>
        {errorMessage && <p className="login-error">{errorMessage}</p>}
      </div>
    </div>
  );
};

export default Login;